<template>
  <div id="myApproval">
    <!-- <div class="search-area">
      <van-sticky :offset-top="44">
        <form action="/">
          <van-search
            :show-action="showCancel"
            v-model="searchValue"
            placeholder="请输入搜索标题"
            @search="onSearch"
            @cancel="onCancel"
          />
        </form>
      </van-sticky>
    </div> -->
    <van-tabs sticky animated swipeable v-model="active">
      <van-tab v-for="(tab,index) in tabs" :key="index" :title="tab.name" :name="tab.type">
        <div class="tab-panel" :ref="tab.data">
          <van-pull-refresh v-model="isLoading" @refresh="getListData(tab.page, tab.finished, tab.data, tab.type, true, false)">
            <img
              slot="loading"
              class="loading-gif-refresh"
              src="../../assets/loading.gif"
            >
            <form>
              <div class="search-area-title">
                <van-row type="flex" justify="space-between">
                  <van-col span="21">
                    <van-search
                      :show-action="showCancel"
                      v-model="searchValue"
                      placeholder="请输入搜索标题"
                      @search="onSearch"
                      @cancel="onCancel"
                    >
                    </van-search>
                  </van-col>
                  <van-col span="3" class="align-center">
                    <img @click="filtratePopup = true" class="search-img" :src="showFiltrateData.length > 0?require('../../assets/documents/shaixuan_active.png'):require('../../assets/documents/shaixuan.png')">
                  </van-col>
                </van-row>
              </div>
              <div v-if="showFiltrateData.length > 0" class="filtershow ">
                <p class="van-ellipsis">
                  <span>筛选：</span>
                  <span class="filter-span" v-for="(item, index) in showFiltrateData" :key="index">
                    {{item.title}}
                  </span>
                </p>
                <img class="filter-x" @click="filtrateCancel" src="../../assets/documents/filterDelete.png">
              </div>
            </form>
            <template v-if="getDataFiled(tab.data).length == 0">
              <div class="no-data-img">
                <img src="../../assets/meeting/no-data.png">
                <p>暂无相关数据</p>
              </div>
            </template>
          <van-list
            v-if="getDataFiled(tab.data).length > 0"
            v-model="loading"
            :finished="getDataFiled(tab.finished)"
            finished-text="没有更多了"
            @load="getListData(tab.page, tab.finished, tab.data, tab.type, false, false)"
          >
          <van-card v-for="(item,index) in getDataFiled(tab.data)" :key="`${index}list`" 
            @click="toDetail(item.id, item.types, item.flow, item.uid)">
              <div slot="thumb">
                <template v-if="item.img">
                  <van-image radius="4px" class="head-img" :src="`${$common.filePath}${item.img}`" />
                </template>
                <template v-else>
                  <img class="head-img" src="../../assets/notification/cell_head.png">
                </template>
              </div>
              <div slot="title">
                <p class="title-class van-ellipsis">{{ item.username }} - {{ item.typename }}</p>
              </div>
              <div slot="desc">
                <p class="desc-info-class van-ellipsis">标题：{{ item.title }}</p>
                <!-- <p class="desc-info-class">流水号：{{ item.number }}</p> -->
                <p class="desc-info-class van-ellipsis">时间：{{ item.date }}</p>
                <!-- 监控则没有以下这些状态值 -->
                <template v-if="active != 3">
                  <template v-if="item.list.pertype == '0'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        未审批
                      </van-row>
                    </p>
                  </template>
                  <template v-if="item.list.pertype == '1'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        您已同意
                      </van-row>
                    </p>
                  </template>
                  <template v-if="item.list.pertype == '2'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        您已拒绝
                      </van-row>
                    </p>
                  </template>
                  <template v-if="item.list.pertype == '3'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        您回退到{{item.regressio.flowname}} - {{item.regressio.name}}审批
                      </van-row>
                    </p>
                  </template>
                  
                  <!-- 等待审批在待办中为未审批 -->
                  <template v-if="active == 1">
                    <template v-if="item.list.pertype == '4'">
                      <p class="desc-box-class" :class="getTypeclass('0')">
                        <van-row :span="24" class="van-ellipsis">
                          未审批
                        </van-row>
                      </p>
                    </template>
                  </template>
                  <!-- 等待审批在办结中为您已同意 -->
                  <template v-if="active == 2">
                    <template v-if="item.list.pertype == '4'">
                      <p class="desc-box-class" :class="getTypeclass('1')">
                        <van-row :span="24" class="van-ellipsis">
                          您已同意
                        </van-row>
                      </p>
                    </template>
                  </template>

                  <template v-if="item.list.pertype == '5'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        流程结束
                      </van-row>
                    </p>
                  </template>
                  <template v-if="item.list.pertype == '6'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        已转交他人会签
                      </van-row>
                    </p>
                  </template>

                  <!-- 别人委托给你 -->
                  <template v-if="active == 1">
                    <template v-if="item.list.pertype == '7'">
                      <p class="desc-box-class" :class="getTypeclass('0')">
                        <van-row :span="24" class="van-ellipsis">
                          {{item.flow.flowname}} - {{item.list.name}}委托给您审批
                        </van-row>
                      </p>
                    </template>
                  </template>
                  
                  <!-- 你委托给别人 显示在待办里面 -->
                  <template v-if="active == 1">
                    <template v-if="item.list.pertype == '11'">
                      <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                        <van-row :span="24" class="van-ellipsis">
                          {{item.flow.flowname}} - 您委托给{{item.list.entrustName}}审批
                        </van-row>
                      </p>
                    </template>
                  </template>

                  <!-- 在委托tab页显示 -->
                  <template v-if="active == 5">
                    <template v-if="item.list.pertype == '11'">
                      <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                        <van-row :span="24" class="van-ellipsis">
                          {{item.flow.flowname}} - 您委托给{{item.list.entrustName}}审批
                        </van-row>
                      </p>
                    </template>
                  </template>
                  <template v-if="item.list.pertype == '8'">
                    <p class="desc-box-class" :class="getTypeclass(item.list.pertype)">
                      <van-row :span="24" class="van-ellipsis">
                        已挂起
                      </van-row>
                    </p>
                  </template>
                  <template v-if="item.list.pertype == '9'">
                    <p class="desc-box-class recover-flex" :class="getTypeclass(item.list.pertype)">
                      流程被撤销
                    <van-button v-if="item.uid == $store.state.userId" type="danger" size="mini" @click.stop="recoverDelete(item.id)">删除</van-button>
                    </p>
                  </template>
                </template>
              </div>
            </van-card>
          </van-list>
          </van-pull-refresh>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 筛选弹出框 -->
    <van-popup v-model="filtratePopup" round lock-scroll position="bottom" class="filtrete-pop"
    @click-overlay="filtrateClose">
      <van-nav-bar title="筛选" class="filtrate-title"/>
      <div class="filtrate-content">
        <van-checkbox-group v-model="filtrateResult" @change="onclick">
          <div v-for="(item,index) in filtrateTree" :key="index" v-if="item.son.length > 0">
            <p class="filtrate-content-title">{{item.typename}}</p>
            <van-row>
              <van-col span="11" v-for="(son, sindex) in item.son" :key="sindex+'son'" :offset="sindex%2==1?'2':''">
                <van-checkbox :ref="`filtrateItem${index}${sindex}`" class="filtrate-choose" 
                :name="son.tplid">{{son.title}}</van-checkbox>
              </van-col>
            </van-row>
          </div>
        </van-checkbox-group>
      </div>
      <van-row type="flex" justify="space-between" class="filtrate-button">
        <van-col span="12">
          <div class="default-class" @click="filtrateCancel">重 置</div>
        </van-col>
        <van-col span="12">
          <div class="info-class" @click="filtrateChose">确 定</div>
        </van-col>
      </van-row>
    </van-popup>
  </div>
</template>
<script type="text/javascript">
  export default {
    data() {
      return {
        active: '0',
        tabs: [/*{
          name: "发起的",
          page: "initiatePage",
          type: 0,
          data: "initiateList",
          finished: 'initiateFinished'
        },*/{
          name: "待办",
          page: "waitPage",
          type: 1,
          data: "waitList",
          finished: 'waitFinished'
        },{
          name: "办结",
          page: "endPage",
          type: 2,
          data: "endList",
          finished: 'endFinished'
        },{
          name: "委托",
          page: "entrustPage",
          type: 5,
          data: "entrustList",
          finished: 'entrustFinished'
        },{
          name: "监控",
          page: "monitorPage",
          type: 3,
          data: "monitorList",
          finished: 'monitorFinished'
        }],
        isLoading: false,
        loading: false,
        // 发起的
        initiatePage: 1,
        initiateList: [],
        initiateFinished: false,
        // 待办
        waitPage: 1,
        waitList: [],
        waitFinished: false,
        // 办结
        endPage: 1,
        endList: [],
        endFinished: false,
        // 委托
        entrustPage: 1,
        entrustList: [],
        entrustFinished: false,
        // 监控
        monitorPage: 1,
        monitorList: [],
        monitorFinished: false,

        searchValue:'',
        showCancel: false,

        fresh: "", //删除流程返回的字段，判断需要刷新数据不

        filtrateTree: [],
        filtratePopup: false, //筛选弹出框控制器
        filtrateResult: [],
        showFiltrateData: [],
      }
    },
    mounted(){
      // console.log('1+' + this.$route.query)
      if (this.$route.query && this.$route.query.tab) {
        this.active = this.$route.query.tab
      }
    },
    activated(){
      // console.log('2+' + JSON.stringify(this.$route.query) )

      this.filtrateTree = []
      this.filtratePopup = false, //筛选弹出框控制器

      this.$bridge.callHandler('navTitle', {title: '我的审批'})
      // this.getListData("initiatePage", "initiateFinished", "initiateList", 0, true, true)
      this.getListData("waitPage", "waitFinished", "waitList", 1, true, true)
      this.getListData("endPage", "endFinished", "endList", 2, true, true)
      this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true, true)
      this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true, true)
      this.getFiltrateData()
      // 从详情自动返回的要判断approvalBack
      if (this.$store.state.approvalBack == 'approvalBack' && this.$route.query && this.$route.query.tab) {
        this.active = parseInt(this.$route.query.tab)
      }
      // approvalBack 之后要清空,不然会影响其他tab页面返回
      this.$store.state.approvalBack = ''

      // if (this.$route.query && this.$route.query.fresh) {
      //   this.fresh = this.$route.query.fresh
      //   console.log(this.fresh)
      // }
      
    },
    watch: {
      'active':{
        handler(newV, oldV){
          // console.log(newV)
        }
      },
      'fresh': {
        handler(newV, oldV){
          if (newV == 'fresh') {
            // console.log(newV)
            // this.getListData("initiatePage", "initiateFinished", "initiateList", 0, true)
            // this.getListData("waitPage", "waitFinished", "waitList", 1, true)
            // this.getListData("endPage", "endFinished", "endList", 2, true)
            // this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true)
            // this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true)
          }
        }
      },
      /**
       * 筛选框
       */
      'filtratePopup': {
        handler(newV, oldV){
          if (this.filtratePopup) {
            this.$bridge.callHandler('navKeepView')
            this.filtrateTree.forEach((tree,index) => {
              tree.son.forEach((son,sonindex) => {
                this.showFiltrateData.forEach((filtrate, findex) => {
                  if (son.tplid == filtrate.tplid) {
                    this.$refs['filtrateItem' + index +  sonindex][0].$el.classList.add("filtrate-choose_active")
                  }
                })
              })
            })
          } else {
            this.$bridge.callHandler('cancelNavKeepView')
          }
        }
      }
    },
    methods: {
      /**
       * 获取列表数据
       * @return {[type]} [description]
       */
      getListData(page, finished, target, type, init, showToast) {
        let self = this
        let tplids = []
        tplids = self.showFiltrateData.map(item => {
          return item.tplid
        })
        if(init) {
          self[page] = 1;
          self[finished] = false;
        }
        let config = {
          method: "POST",
          url: `${self.$common.basePath}aatp5/public/index.php/workclass/work_class/work_list`,
          data: {
            page: self[page]++ ,
            type: type,
            user_id: self.$store.state.userId,
            title: self.searchValue,
            tplid: tplids
          }
        }
        if(showToast) {
          self.$toast({
            duration: 0,
            forbidClick: true,
            className: 'loading-toast',
            icon: require('../../assets/loading.gif'),
          })
        }
        if(!self[finished] || init) {
          self.$axios(config).then(res => {
            self.loading = false
            self[target] = init?res.data.data : self[target].concat(res.data.data)
            if(self[target].length >= res.data.count) {
              self[finished] = true 
            }
            self.isLoading = false
            self.$toast.clear()
          }).catch(err => {
            self.$toast.clear()
            self[finished] = true 
            self[target] = []
            self.loading = false
          })
        }
      },
      getDataFiled(dataFiled) {
        return this[dataFiled]
      },
      /**
       * 搜索栏
       * @param  {[type]} type [description]
       * @return {[type]}      [description]
       */
      onSearch (value) {
        if (value) {
          this.showCancel = true
        }
        if (this.active == '1') {
          this.getListData("waitPage", "waitFinished", "waitList", 1, true, true)
        } else if (this.active == '2') {
          this.getListData("endPage", "endFinished", "endList", 2, true, true)
        } else if (this.active == '5') {
          this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true, true)
        } else if (this.active == '3') {
          this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true, true)
        }
      },
      /**
       * 取消搜索
       * @return {[type]} [description]
       */
      onCancel () {
        this.showCancel = false
        // this.getListData("initiatePage", "initiateFinished", "initiateList", 0, true, true)
        this.getListData("waitPage", "waitFinished", "waitList", 1, true, true)
        this.getListData("endPage", "endFinished", "endList", 2, true, true)
        this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true, true)
        this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true, true)
      },

      /*
        * 获取筛选数据
       */
      getFiltrateData() {
        let config = {
          method: "post",
          url: `${this.$common.basePath}workclass.php`,
          data: {
            do: "workaddlist",
            user_id: this.$store.state.userId
          }
        }
        this.$axios(config).then(res => {
          this.filtrateTree = res.data
        }).catch(err => {
          this.$toast(err.msg)
        })
      },

      /**
       * 选择事件
       * @return {[type]} [description]
       */
      onclick(e) {
        // console.log(this.filtrateResult)
        let self = this
        // 给元素动态添加class
        self.filtrateTree.forEach((tree,index) => {
          tree.son.forEach((son,sonindex) => {
            if (self.$refs['filtrateItem' + index + sonindex][0].checked) {
              // console.log(1)
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.add("filtrate-choose_active")
            } else {
              // console.log(2)
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.remove("filtrate-choose_active")
            }
          })
        })
      },
      /**
       * 点击蒙层关闭筛选框
       * @return {[type]} [description]
       */
      filtrateClose() {
        let self = this
        // 给元素动态重置class
        self.filtrateTree.forEach((tree,index) => {
          tree.son.forEach((son,sonindex) => {
            if (self.$refs['filtrateItem' + index + sonindex][0].checked) {
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.remove("filtrate-choose_active")
            }
            self.showFiltrateData.forEach((filtrate, findex) => {
              if (son.tplid == filtrate.tplid) {
                self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.add("filtrate-choose_active")
              }
            })
          })
        })
        // 同时将v-model删掉
        self.filtrateResult = self.showFiltrateData.map(item => {
          return item.tplid
        })
      },
      /** 
       * 重置筛选--还原所有tab
       */
      filtrateCancel() {
        let self = this
        // 给元素动态添加class
        self.filtrateTree.forEach((tree,index) => {
          tree.son.forEach((son,sonindex) => {
            if (self.$refs['filtrateItem' + index + sonindex][0]) {
              // console.log(1)
              self.$refs['filtrateItem' + index +  sonindex][0].$el.classList.remove("filtrate-choose_active")
            }
          })
        })
        this.filtrateResult = []
        this.showFiltrateData = []
        // this.filtratePopup = false
        // this.getListData("initiatePage", "initiateFinished", "initiateList", 0, true, true)
        this.getListData("waitPage", "waitFinished", "waitList", 1, true, true)
        this.getListData("endPage", "endFinished", "endList", 2, true, true)
        this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true, true)
        this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true, true)
      },

      /**
       * 筛选
       * @return {[type]} [description]
       */
      filtrateChose() {
        this.filtratePopup = false
        // 筛选条件显示---数据处理
        if (this.filtrateResult.length > 0) {
          // 先清空数据
          this.showFiltrateData = []
            this.filtrateResult.forEach(newItem => {
              this.filtrateTree.forEach(item => {
                item.son.forEach(child => {
                  if (newItem == child.tplid) {
                    this.showFiltrateData.push(child)
                  }
                })
              })
            })
          } else {
            this.showFiltrateData = []
          }
        this.getListData("waitPage", "waitFinished", "waitList", 1, true, true)
        this.getListData("endPage", "endFinished", "endList", 2, true, true)
        this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true, true)
        this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true, true)
      },

      getTypename(type) {
        let typename = ""
        switch(type) {
          case '0':
            typename = '未审批'
            break;
          case '1':
            typename = '审批'
            break;
          case '2':
            typename = '拒绝'
            break;
          case '3':
            typename = '退回'
            break;
          case '4':
            typename = '等待审批'
            break;
          case '5':
            typename = '结束'
            break;
          case '6':
            typename = '会签'
            break;
          case '7':
            typename = '委托'
            break;
          case '8':
            typename = '挂起'
            break;
          case '9':
            typename = '撤销'
            break;
          default:
            typename = '结束'
        }
        return typename;
      },
      getTypeclass(type) {
        let typeclass = ''
        switch(type) {
          case '0':
            typeclass = 'wait-class'
            break;
          case '1':
          case '4':
          case '6':
          case '7':
          case '8':
            typeclass = 'agreen-class'
            break;
          case '2':
          case '3':
            typeclass = 'defined-class'
            break;
          case '9':
            typeclass = 'revocation-class'
            break;
          case '5':
            typeclass = 'close-class'
          default:
            typeclass = 'close-class'
        }
        return typeclass;
      },
      /**
       * 点击进去详情页面
       * @param  {[type]} id   [description]
       * @param  {[type]} type [description]
       * @return {[type]}      [description]
       */
      toDetail(id, types, flow, uid) {
          this.$router.push({ name:'approvalInfo', query:{workid: id, type: types, step: flow.flownum, uid: uid} })
      },
      /**
       * 删除
       * @return {[type]} [description]
       */
      recoverDelete (id) {
        this.$bridge.callHandler('navKeepView')
        this.$dialog.confirm({
          title:'警告',
          message: '是否确认删除该流程？'
        }).then(() => {
          this.$bridge.callHandler('cancelNavKeepView')
          let config = {
            method: "post",
            url: `${this.$common.basePath}workclass.php`,
            data: {
              do: "delete",
              user_id: this.$store.state.userId,
              workid: id
            }
          }
          this.$axios(config).then(res => {
            this.$toast('删除成功')
            // this.getListData("initiatePage", "initiateFinished", "initiateList", 0, true, true)
            this.getListData("waitPage", "waitFinished", "waitList", 1, true, true)
            this.getListData("endPage", "endFinished", "endList", 2, true, true)
            this.getListData("entrustPage", "entrustFinished", "entrustList", 5, true, true)
            this.getListData("monitorPage", "monitorFinished", "monitorList", 3, true, true)
            // 原生刷新页面
            this.$bridge.callHandler('reloadView', {date: parseInt(new Date().getTime())})
          }).catch(err => {
            this.$toast(err.msg)
          })
        }).catch(() => {
          this.$bridge.callHandler('cancelNavKeepView')
        })
      }
    }
  }
</script>
<style type="text/css" lang="less" scoped>
  .tab-panel  {
    -webkit-overflow-scrolling: touch;
    // height: calc(100vh - 94px);
    // overflow-y: auto;
    background: #f5f5f5;
    // padding-top: 53px;
    .van-list {
      // padding-top: 12px;
      min-height: calc(100vh - 110px);
    }
  }
  p{
    margin: 0;
  }
  .head-img {
    width: 40px;
    height: 40px;
    border-radius: 4px;
  }
  .title-class {
    font-size: 17px;
    color: #333333;
    font-weight: bold;
    margin-bottom: 5px;
  }
  .desc-info-class {
    font-size: 14px;
    color: #999999;
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .desc-box-class {
    margin-top: 5px;
    // height: 40px;
    font-size: 14px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    // padding-left: 10px;
    // padding-right: 10px;
  }
  .margin-l-13 {
    margin-left: 13px;
  }
  // 未审批
  .wait-class {
    color: #F5A703
  }
  // 同意
  .agreen-class {
    // background-color: rgba(46, 121, 255, 0.06);
    color: rgb(46, 121, 255);
  }
  // 退回
  .defined-class {
    // background-color: rgba(245, 75, 3, 0.06);
    color: rgb(245, 75, 3);
  }
  // 结束
  .close-class {
    // background-color: rgba(1, 191, 101, 0.06);
    color: rgb(1, 191, 101);
  }
  // 撤销
  .revocation-class {
    // background-color: rgba(245, 167, 3, 0.06);
    color: rgb(245, 167, 3);
  }
  .no-data-img {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40% 0;
    background-color: #f5f5f5;

    img {
      width: 180px;
      height: 106px;
      text-align: center;
    }

    p{
      font-size: 17px;
      color: #333333
    }
  }
  .recover-flex {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
</style>
<style type="text/css" lang="less">
  #myApproval {
    -webkit-overflow-scrolling: touch;
    height: calc(100vh - 50px);
    background-color: #f5f5f5;
    position: static;

    .search-area {
      margin-top: 12px;
      .van-cell {
        line-height: 25px;
      }
    }

    .van-tab span {
      font-size: 14px;
    }
    .van-tab {
      flex-basis: 20%!important;
    }
    .van-tabs__wrap {
      padding: 0 40px;
      background-color: #fff;
    }
    .van-tabs__line {
      width: 55.5px!important;
    }
    .van-card {
      background-color: #fff;
      margin-top: 0;
      padding: 15px 15px 0 15px;
    }
    .van-card__thumb {
      width: auto;
      height: auto;
      margin-right: 12px;
    }
    .van-card__content{
      min-height: auto;
      padding-bottom: 15px;
      border-bottom: 1px solid #F5F5F5;
    }
  }
</style>